package com.ycrlkj.android.modulespublic.common.net.di;

import android.util.Log;

import androidx.annotation.NonNull;

import com.ycrlkj.android.modulespublic.common.net.Interceptor.ApplicationInterceptor;
import com.ycrlkj.android.modulespublic.common.net.Interceptor.NetworkInterceptor;
import com.ycrlkj.android.modulesbase.libbase.utils.PropertiesUtil;
import java.util.concurrent.TimeUnit;
import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides;
import dagger.hilt.InstallIn;
import dagger.hilt.android.components.ApplicationComponent;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

@InstallIn(ApplicationComponent.class) //装载到ApplicationComponent中
@Module //配合 @Provides 注解实现注入
public class NetworkModule {

    @Singleton
    @Provides
    Retrofit provideRetrofit(OkHttpClient client) {
        String baseUrl = PropertiesUtil.getProperty("baseUrl");
        return new Retrofit.Builder()
                .baseUrl(baseUrl)
                .client(client)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())//请求转化, 原生请求返回 Call 对象, 加入此配置转为返回 Observable 对象
                .addConverterFactory(GsonConverterFactory.create())//使用 Gson 做 json转换
                .build();
    }


    @Singleton
    @Provides
    OkHttpClient provideOkHttpClient() {
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
            @Override
            public void log(@NonNull String message) {
                Log.e("ming", "系统日志请求拦截器: message = " + message);
            }
        }).setLevel(HttpLoggingInterceptor.Level.BODY);

        return new OkHttpClient
                .Builder()
                .connectTimeout(2, TimeUnit.SECONDS)
                .writeTimeout(120, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)

                .addInterceptor(new ApplicationInterceptor())//添加自定义应用拦截器
                .addInterceptor(new NetworkInterceptor())//添加自定义网络拦截器
                .addInterceptor(interceptor)
                .build();
    }

}
